<script setup lang="ts">
import ScSelector from "@/components/scSelector/ScSelector.vue";
import type { PropType } from "vue";
import { deepClone } from "@/utils";
import { getActPageFlagsApi } from "@/api/activity";
import { mode } from "crypto-js";

const props = defineProps({
  modelValue: {
    type: Object as PropType<any>,
  },
  subType: {
    type: String,
  },
  lottery: {
    type: Boolean,
    default: false,
  },
  prizeAreas: {
    type: Array as PropType<Array<any>>,
    required: true,
  },
  prefix: {
    type: String,
    default: "",
  },
});

const emits = defineEmits([
  "update:modelValue",
  "change",
  "addPool",
  "addPrize",
]),
  currencyList: any = inject("currencyList", []),
  // activityList: any = inject("activityList", []),
  activityBaseInfo: any = inject("activityBaseInfo", {}),
  zoneList: any = inject("zoneList");

const activityPageFlagList = ref({});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      if (val.rewardType) stopWatch();
      else return;
      if (val.rewardType == "COIN" && val.coinId) {
        let currency = currencyList.value.find(
          (item: any) => item.id == val.coinId
        );
        if (currency) props.modelValue.name = currency.name;
      } else if (val.rewardType == "PRIZE" && val.prizeSpec) {
        let pool = productPool.value[val.prizeArea];
        let product = pool.prizeInfos ? pool.prizeInfos[val.prizeId] : null;
        let spec = product.prizeSpecifications[val.prizeSpec];
        props.modelValue.name = spec.name;
        props.modelValue.thumbnailUrl = spec.thumbnailUrl;
        if (pool && !pool.id) {
          props.modelValue.prizeAreaUid = val.prizeArea;
        }
        if (product && !product.id) {
          props.modelValue.prizeUid = val.prizeId;
        }
        if (spec && !spec.id) {
          props.modelValue.prizeSpecUid = val.prizeSpec;
        }
      } else if (val.rewardType == "LOTTERY") {
        let pool = prizePool.value[val.lotteryArea];
        if (pool && !pool.id) {
          props.modelValue.lotteryAreaUid = val.lotteryArea;
        }
      } else if (val.rewardType === "TICKET") {
        if (!val.ticketAct) {
          val.ticketAct = "local";
        } else {
          if (val.ticketAct === activityBaseInfo.value.id) {
            val.ticketAct = "local";
          } else {
            changeActivity(val.ticketAct)
          };
        }
      }
      updateData();
    });
  },
  { immediate: true, deep: true }
);
watch(() => props.modelValue.ticketAct, (val) => {
  if (props.modelValue.rewardType === "TICKET") {
    if (val && val != 'local') {
      props.modelValue.ticketPageFlag = ''
      updateData();
      changeActivity(val)
    }
  }
})


const productPool = computed(() => {
  let poolType2: any = props.prizeAreas.filter((pool: any) => pool.type == 2);
  let newPool: any = {};
  if (poolType2 && poolType2.length > 0) {
    poolType2 = deepClone(poolType2);
    for (let i = 0; i < poolType2.length; i++) {
      let pool = poolType2[i];
      let prizeInfos = pool.prizeInfos;
      pool.prizeInfos = {};
      for (let j = 0; j < prizeInfos.length; j++) {
        let prize = prizeInfos[j];
        let prizeSpecifications = prize.prizeSpecifications;
        prize.prizeSpecifications = {};
        if (prize.onlineStatus == 1) {
          pool.prizeInfos[prize.id ? prize.id : prize.uid] = prize;
          for (let k = 0; k < prizeSpecifications.length; k++) {
            let spec = prizeSpecifications[k];
            if (prize.prizeType == 2)
              spec.name = `${spec.name}*${spec.rewardGoodsNum}`;
            prize.prizeSpecifications[spec.id ? spec.id : spec.uid] = {
              ...spec,
              disabled: spec.onlineStatus == 1 ? false : true,
            };
          }
        } else
          pool.prizeInfos[prize.id ? prize.id : prize.uid] = {
            ...prize,
            disabled: true,
          };
      }
      newPool[pool.id ? pool.id : pool.uid] = pool;
    }
  }
  return newPool;
});

const prizePool = computed(() => {
  let pool = props.prizeAreas.filter((pool: any) => pool.type == 1);
  let newPool: any = {};
  for (let i = 0; i < pool.length; i++) {
    newPool[pool[i].id ? pool[i].id : pool[i].uid] = pool[i];
  }
  return newPool;
});

// 切换奖励类型
const changeRewardType = () => {
  // 清空奖池、奖品和规格id
  props.modelValue.lotteryArea = "";
  props.modelValue.lotteryAreaUid = "";
  props.modelValue.prizeArea = "";
  props.modelValue.prizeAreaUid = "";
  props.modelValue.prizeId = "";
  props.modelValue.prizeUid = "";
  props.modelValue.prizeSpec = "";
  props.modelValue.prizeSpecUid = "";
  props.modelValue.ticketAct = "";
  props.modelValue.ticketPageFlag = "";
  props.modelValue.rewardNum = 1;
  props.modelValue.name = "";
  props.modelValue.coinId = "";
  props.modelValue.effectTime = null
  props.modelValue.expireTime = null
  updateData();
};

// 切换代币类型
const changeCurrency = () => {
  let currency = currencyList.value.find(
    (item: any) => item.id == props.modelValue.coinId
  );
  if (currency) {
    props.modelValue.name = currency.name;
    props.modelValue.thumbnailUrl = currency.logo;
  }
  updateData();
};

// 切换奖池
const changePool = () => {
  // 清空奖品和规格id
  props.modelValue.lotteryAreaUid = "";
  props.modelValue.prizeAreaUid = "";
  props.modelValue.prizeUid = "";
  props.modelValue.prizeId = "";
  props.modelValue.prizeSpecUid = "";
  props.modelValue.prizeSpec = "";
  if (props.modelValue.rewardType == "PRIZE") {
    // 新建奖池配置uid
    if (
      prizePool.value[props.modelValue.prizeArea] &&
      !prizePool.value[props.modelValue.prizeArea].id
    ) {
      props.modelValue.prizeAreaUid = props.modelValue.prizeArea;
    }
  } else if (props.modelValue.rewardType == "LOTTERY") {
    // 新建奖池配置uid
    if (
      prizePool.value[props.modelValue.lotteryArea] &&
      !prizePool.value[props.modelValue.lotteryArea].id
    ) {
      props.modelValue.lotteryAreaUid = props.modelValue.lotteryArea;
    }
  }
  updateData();
};

// 切换奖品
const changePrize = () => {
  // 清空规格id
  props.modelValue.prizeSpec = "";
  props.modelValue.prizeSpecUid = "";
  updateData();
};

// 切换奖品规格
const changeSpec = () => {
  let poolId = props.modelValue.prizeArea;
  let prizeId = props.modelValue.prizeId;
  let specId = props.modelValue.prizeSpec;
  let spec =
    productPool.value[poolId].prizeInfos[prizeId].prizeSpecifications[specId];
  props.modelValue.name = spec.name;
  props.modelValue.thumbnailUrl = spec.thumbnailUrl;

  // 新建奖池配置uid
  let pool = productPool.value[props.modelValue.prizeArea];
  if (pool) {
    if (!pool.id) {
      props.modelValue.prizeAreaUid = props.modelValue.prizeArea;
    }
    let prize = pool.prizeInfos[props.modelValue.prizeId];
    if (prize) {
      // 新建奖品配置uid
      if (!prize.id) {
        props.modelValue.prizeUid = props.modelValue.prizeId;
      }
      let spec = prize.prizeSpecifications[props.modelValue.prizeSpec];
      if (spec) {
        if (!spec.id) {
          props.modelValue.prizeSpecUid = props.modelValue.prizeSpec;
        }
      }
    }
  }

  updateData();
};

// 切换活动
const changeActivity = async (id: number | string) => {
  if (id === "local") return;
  const rs = await getActPageFlagsApi({ id });
  if (rs.code == 200) {
    activityPageFlagList.value[id] = rs.payload;
  }
};

// 添加奖池
const addPool = () => {
  emits("addPool");
};

// 添加奖品
const addPrize = () => {
  let poolId = props.modelValue.prizeArea;
  let poolIndex = Object.keys(productPool.value).findIndex(
    (item: any) => item == poolId
  );
  emits("addPrize", poolIndex);
};

//限制生效时间
const limitEffect = (date) => {
  const now = new Date().getTime()
  return date.getTime() < now - 86400000

}

const updateData = () => {
  emits("update:modelValue", props.modelValue);
  emits("change");
};
</script>
<template>
  <el-form-item label-width="10px" :prop="`${prefix}rewardType`" :rules="[
    {
      required: true,
      message: '请选择奖励类型',
      trigger: 'change',
    },
  ]">
    <el-select v-model="modelValue.rewardType" placeholder="请选择" style="width: 100px" @change="changeRewardType">
      <el-option v-if="subType == 'WeekSign' || subType == 'VoteOnly'" label="无" value="NONE" />
      <el-option label="积分" value="COIN"></el-option>
      <el-option label="奖品" value="PRIZE"></el-option>
      <el-option label="成长值" value="GROWTH"></el-option>
      <template v-if="lottery">
        <el-option label="抽奖机会" value="LOTTERY"></el-option>
      </template>
      <el-option label="活动参与机会" value="TICKET"></el-option>
    </el-select>
  </el-form-item>
  <template v-if="modelValue.rewardType == 'COIN'">
    <el-form-item label-width="10px" :prop="`${prefix}rewardNum`" :rules="[
      {
        required: true,
        message: '请输入积分数量',
        trigger: 'blur',
      },
    ]">
      <EasyNumberInput v-model="modelValue.rewardNum" :min="1" :max="9999" unit="个" :precision="0" @change="updateData" />
    </el-form-item>
    <el-form-item label-width="10px" :prop="`${prefix}coinId`" :rules="[
      {
        required: true,
        message: '请选择积分类型',
        trigger: 'change',
      },
    ]">
      <el-select v-model="modelValue.coinId" placeholder="请选择" style="width: 100px" @change="changeCurrency">
        <el-option v-for="(item, key) in currencyList" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
  </template>
  <template v-if="modelValue.rewardType == 'PRIZE'">
    <el-form-item label-width="10px" :prop="`${prefix}prizeArea`" :rules="[
      {
        required: true,
        message: '请选择奖池',
        trigger: 'change',
      },
    ]">
      <el-select v-model="modelValue.prizeArea" placeholder="请选择奖池" style="width: 120px" @change="changePool">
        <el-option v-for="(pool, key) in productPool" :label="pool.name"
          :value="isNaN(Number(key)) ? key : Number(key)" />
        <el-option value="" v-if="!activityBaseInfo.id">
          <el-button link icon="plus" @click.stop="addPool">添加奖池</el-button>
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="modelValue.prizeArea" label-width="10px" :prop="`${prefix}prizeId`" :rules="[
      {
        required: true,
        message: '请选择奖品',
        trigger: 'change',
      },
    ]">
      <el-select v-model="modelValue.prizeId" placeholder="请选择奖品" style="width: 120px" @change="changePrize">
        <el-option v-for="(prize, key) in productPool[modelValue.prizeArea].prizeInfos" :label="prize.name"
          :value="isNaN(Number(key)) ? key : Number(key)" :disabled="prize.disabled">
          <span style="float: left">{{ prize.name }}</span>
          <span v-if="prize.disabled" style="float: right; color: #999999; font-size: 10px">（已下架）</span>
        </el-option>
        <el-option value="" v-if="!activityBaseInfo.id">
          <el-button link icon="plus" @click.stop="addPrize">添加奖品</el-button>
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="modelValue.prizeArea && modelValue.prizeId" label-width="10px" :prop="`${prefix}prizeSpec`"
      :rules="[
        {
          required: true,
          message: '请选择奖品规格',
          trigger: 'change',
        },
      ]">
      <el-select v-model="modelValue.prizeSpec" placeholder="请选择规格" style="width: 120px" @change="changeSpec">
        <el-option v-for="(spec, key) in productPool[modelValue.prizeArea].prizeInfos[
          modelValue.prizeId
        ].prizeSpecifications" :label="spec.name" :value="isNaN(Number(key)) ? key : Number(key)"
          :disabled="spec.disabled">
          <span style="float: left">{{ spec.name }}</span>
          <span v-if="spec.disabled" style="float: right; color: #999999; font-size: 10px">（已下架）</span>
        </el-option>
      </el-select>
    </el-form-item>
  </template>
  <template v-if="modelValue.rewardType == 'LOTTERY'">
    <el-form-item label-width="10px" :prop="`${prefix}lotteryArea`" :rules="[
      {
        required: true,
        message: '请选择奖池',
        trigger: 'change',
      },
    ]">
      <el-select v-model="modelValue.lotteryArea" placeholder="请选择奖池" style="width: 120px" @change="changePool">
        <el-option v-for="(pool, key) in prizePool" :label="pool.name" :value="isNaN(Number(key)) ? key : Number(key)" />
        <el-option value="" v-if="!activityBaseInfo.id">
          <el-button link icon="plus" @click.stop="addPool">添加奖池</el-button>
        </el-option>
      </el-select>
    </el-form-item>
    <!-- <el-form-item
          label-width="10px"
          :prop="`itemList.${index}.lotteryImmediate`"
          ><el-checkbox
            v-model="item.lotteryImmediate"
            label="立即抽奖"
            :true-label="1"
            :false-label="0"
        /></el-form-item> -->
  </template>
  <template v-else-if="modelValue.rewardType == 'TICKET'">
    <el-form-item label-width="10px" :prop="`${prefix}ticketAct`" :rules="[
      {
        required: true,
        message: '请选择活动',
        trigger: 'change',
      },
    ]">
      <ScSelector v-model="modelValue.ticketAct" type="activity" @change-selected="onChangeAct">
        <template #expand-pop="{ data }">
          <div v-if="data" class="detail-container">
            <div class="detail-text">
              <h3>
                {{ data.info.name }}
                <el-tag :type="data.info.status == 2 || data.info.status == 1
                  ? ''
                  : 'danger'
                  ">{{
    data.info.status == 2
    ? "已上线"
    : data.info.status == 1
      ? "预上线"
      : "已下线"
  }}</el-tag>
              </h3>
              <div class="detail-text_line">
                开始时间：{{ $filters.dateFormat(data.info.startTime) }}
              </div>
              <div class="detail-text_line">
                结束时间：
                {{ $filters.dateFormat(data.info.endTime) }}
              </div>
              <div class="detail-text_line">
                所属机构：
                {{ data.info.insName }}
              </div>
              <div>
                所属分组：
                {{ data.info.groupName || "全部" }}
              </div>
              <div>
                活动备注：
                {{ data.info.remark || "暂无" }}
              </div>
            </div>
            <div class="detail-img" v-if="data.info.coverUrl">
              <img :src="data.info.coverUrl" alt="" />
            </div>
          </div>
        </template>
      </ScSelector>
    </el-form-item>
    <el-form-item label-width="10px" :prop="`${prefix}ticketPageFlag`" :rules="[
      {
        required: true,
        message: '请选择活动区域',
        trigger: 'change',
      },
    ]">
      <el-select v-model="modelValue.ticketPageFlag" placeholder="请选择活动区域" style="width: 120px">
        <template v-if="modelValue.ticketAct === 'local'">
          <el-option v-for="zone in zoneList" :label="zone.pageArea.name" :value="zone.pageArea.pageFlag" />
        </template>
        <template v-else>
          <el-option v-for="(activity, key) in activityPageFlagList[
            modelValue.ticketAct
          ]" :label="activity.name" :value="activity.pageFlag" />
        </template>
      </el-select>
    </el-form-item>
  </template>
  <template v-if="modelValue.rewardType == 'GROWTH'">
    <el-form-item label-width="10px" :prop="`${prefix}rewardNum`" :rules="[
      {
        required: true,
        message: '请输入成长值数量',
        trigger: 'blur',
      },
    ]">
      <EasyNumberInput v-model="modelValue.rewardNum" :min="1" :max="9999" unit="个" :precision="0" @change="updateData" />
    </el-form-item>
    <el-form-item label-width="10px" :prop="`${prefix}effectTime`" :rules="[
      {
        required: true,
        message: '请选择生效时间',
        trigger: 'blur',
      },
    ]">
      <el-date-picker v-model="modelValue.effectTime" type="datetime" placeholder="生效时间" value-format="x"
        :disabled-date="limitEffect" />
    </el-form-item>
    <el-form-item label-width="10px" :prop="`${prefix}expireTime`" :rules="[
      {
        required: true,
        message: '请选择失效时间',
        trigger: 'blur',
      },
    ]"> <el-date-picker v-model="modelValue.expireTime" type="datetime" placeholder="失效时间"
        :default-time="new Date(2000, 1, 1, 23, 59, 59)" value-format="x" :disabled-date="limitEffect" /></el-form-item>
  </template>
</template>
<style lang="scss" scoped>
.detail-img{
  img{
    max-width: 100%;
  }
}
</style>
